#include "linkedlistwindow.h"

// ===================================================
// LinkedListVisualWidget 实现
// ===================================================

LinkedListVisualWidget::LinkedListVisualWidget(QWidget *parent)
    : QWidget(parent), m_head(nullptr), m_currentNode(nullptr), m_previousNode(nullptr),
    m_newNode(nullptr), m_showNewNode(false), m_breakConnection(false),
    m_breakNode(nullptr), m_animationStep(0), m_targetPosition(0),
    m_drawNodes(nullptr), m_drawNodesSize(0), m_drawNodesCapacity(0)
{
    setMinimumSize(800, 300);
}

LinkedListVisualWidget::~LinkedListVisualWidget()
{
    // 释放动态数组内存
    delete[] m_drawNodes;
}

void LinkedListVisualWidget::setLinkedListData(ListNode* head, ListNode* currentNode,
                                               ListNode* previousNode, ListNode* newNode,
                                               bool showNewNode, bool breakConnection,
                                               ListNode* breakNode, const QString& operationType,
                                               int animationStep, int targetPosition)
{
    m_head = head;
    m_currentNode = currentNode;
    m_previousNode = previousNode;
    m_newNode = newNode;
    m_showNewNode = showNewNode;
    m_breakConnection = breakConnection;
    m_breakNode = breakNode;
    m_operationType = operationType;
    m_animationStep = animationStep;
    m_targetPosition = targetPosition;
    update();
}

void LinkedListVisualWidget::computeDrawArea()
{
    // 计算链表节点数量
    int nodeCount = 0;
    ListNode* current = m_head;
    while (current != nullptr) {
        nodeCount++;
        current = current->next;
    }

    // 如果容量不足，重新分配数组
    if (nodeCount > m_drawNodesCapacity) {
        delete[] m_drawNodes;
        m_drawNodesCapacity = nodeCount + 10; // 额外分配一些空间
        m_drawNodes = new DrawNode[m_drawNodesCapacity];
    }
    m_drawNodesSize = nodeCount;

    int widthLeft = 50;
    int widthRight = 30;
    int height = 40;
    int spacing = 20;
    int padding_left = 40;
    int padding_top = rect().height() / 2 - height;

    current = m_head;
    int index = 0;

    while (current != nullptr && index < m_drawNodesCapacity) {
        DrawNode& node = m_drawNodes[index];
        node.rectLeft = QRect(
            padding_left + index * (widthLeft + widthRight + spacing),
            padding_top, widthLeft, height
            );
        node.rectRight = QRect(
            padding_left + widthLeft + index * (widthLeft + widthRight + spacing),
            padding_top, widthRight, height
            );
        node.point = QPoint(
            node.rectRight.x() + node.rectRight.width() / 2,
            node.rectRight.y() + node.rectRight.height() / 2
            );
        node.value = current->data;

        // 检查节点状态
        ListNode* temp = m_head;
        for (int i = 0; i < index && temp; i++) {
            temp = temp->next;
        }
        node.isCurrent = (temp == m_currentNode);
        node.isPrevious = (temp == m_previousNode);

        current = current->next;
        index++;
    }

    // NULL节点位置
    if (m_drawNodesSize > 0) {
        m_nullRect = QRect(
            padding_left + m_drawNodesSize * (widthLeft + widthRight + spacing),
            padding_top, widthLeft, height
            );
    }
}

void LinkedListVisualWidget::drawNode(QPainter& painter, const DrawNode& node, int index)
{
    // 设置节点颜色
    QPen rectPen(Qt::black, 2, Qt::SolidLine);
    QPen valuePen(Qt::black, 2, Qt::SolidLine);
    QColor fillColor = Qt::transparent;

    if (node.isCurrent) {
        rectPen = QPen(QColor(255, 138, 39), 2, Qt::SolidLine);
        valuePen = QPen(Qt::white, 2, Qt::SolidLine);
        fillColor = QColor(255, 138, 39);
    } else if (node.isPrevious) {
        rectPen = QPen(QColor(46, 187, 209), 2, Qt::SolidLine);
    }

    // 绘制节点矩形
    if (fillColor != Qt::transparent) {
        painter.fillRect(node.rectLeft, fillColor);
    }
    painter.setPen(rectPen);
    painter.drawRect(node.rectLeft);
    painter.drawRect(node.rectRight);

    // 绘制中间点
    painter.setPen(QPen(Qt::black, 8, Qt::SolidLine));
    painter.drawPoint(node.point);

    // 绘制值
    painter.setPen(valuePen);
    QFont font("Microsoft YaHei", 15, QFont::Bold);
    painter.setFont(font);
    painter.drawText(node.rectLeft, Qt::AlignCenter, QString::number(node.value));

    // 绘制箭头指向下一节点或 NULL
    QPoint startPoint = node.point;
    QPoint endPoint;

    if (index < m_drawNodesSize - 1) {
        const DrawNode& nextNode = m_drawNodes[index + 1];
        endPoint = QPoint(nextNode.rectLeft.x(), nextNode.rectLeft.y() + nextNode.rectLeft.height() / 2);
    } else {
        endPoint = QPoint(m_nullRect.x(), m_nullRect.y() + m_nullRect.height() / 2);
    }

    painter.setPen(QPen(Qt::black, 2, Qt::SolidLine));
    painter.drawLine(startPoint, endPoint);

    // 绘制箭头
    painter.drawLine(QLine(endPoint.x() - 5, endPoint.y() - 5, endPoint.x(), endPoint.y()));
    painter.drawLine(QLine(endPoint.x() - 5, endPoint.y() + 5, endPoint.x(), endPoint.y()));
}

// ===================================================
// 绘制新节点及箭头
// ===================================================
void LinkedListVisualWidget::drawNewNode(QPainter& painter)
{
    if (!m_newNode || !m_showNewNode) return;

    int widthLeft = 50;
    int widthRight = 30;
    int height = 40;
    int padding_left = 40;
    int padding_top = rect().height() / 2 - height;

    // 新节点位置（在链表下方）
    QRect newRectLeft = QRect(padding_left + 100, padding_top + 100, widthLeft, height);
    QRect newRectRight = QRect(padding_left + 100 + widthLeft, padding_top + 100, widthRight, height);
    QPoint point = QPoint(newRectRight.x() + newRectRight.width() / 2,
                          newRectRight.y() + newRectRight.height() / 2);

    // 绘制新节点
    painter.setPen(QPen(QColor(82, 188, 105), 2, Qt::SolidLine));
    painter.fillRect(newRectLeft, QColor(82, 188, 105));
    painter.drawRect(newRectLeft);
    painter.drawRect(newRectRight);

    painter.setPen(QPen(Qt::black, 8, Qt::SolidLine));
    painter.drawPoint(point);

    painter.setPen(QPen(Qt::white, 2, Qt::SolidLine));
    QFont font("Microsoft YaHei", 15, QFont::Bold);
    painter.setFont(font);
    painter.drawText(newRectLeft, Qt::AlignCenter, QString::number(m_newNode->data));

    // 绘制新节点箭头
    if (m_animationStep >= 22) {
        painter.setPen(QPen(QColor(82, 188, 105), 2, Qt::SolidLine));

        if (m_newNode->next) {
            // 找到后继节点位置
            ListNode* target = m_newNode->next;
            int targetIndex = 0;
            ListNode* current = m_head;
            while (current && current != target) {
                current = current->next;
                targetIndex++;
            }

            if (targetIndex < m_drawNodesSize) {
                const DrawNode& nextNode = m_drawNodes[targetIndex];
                QPoint endPoint(nextNode.rectLeft.x(), nextNode.rectLeft.y() + nextNode.rectLeft.height()/2);
                painter.drawLine(point, endPoint);

                // 箭头
                painter.drawLine(QLine(endPoint.x() - 5, endPoint.y() - 5, endPoint.x(), endPoint.y()));
                painter.drawLine(QLine(endPoint.x() - 5, endPoint.y() + 5, endPoint.x(), endPoint.y()));
            }
        } else {
            // 指向 NULL
            QPoint nullPoint(m_nullRect.x(), m_nullRect.y() + m_nullRect.height()/2);
            painter.drawLine(point, nullPoint);
            painter.drawLine(QLine(nullPoint.x() - 5, nullPoint.y() - 5, nullPoint.x(), nullPoint.y()));
            painter.drawLine(QLine(nullPoint.x() - 5, nullPoint.y() + 5, nullPoint.x(), nullPoint.y()));
        }
    }

    // 绘制前驱节点到新节点的连接线
    if (m_previousNode && m_animationStep >= 21) {
        ListNode* current = m_head;
        int prevIndex = 0;
        while (current && current != m_previousNode) {
            current = current->next;
            prevIndex++;
        }

        if (prevIndex < m_drawNodesSize) {
            QPoint prevPoint = m_drawNodes[prevIndex].point;
            QPoint endPoint(newRectLeft.x(), newRectLeft.y() + newRectLeft.height()/2);
            painter.setPen(QPen(QColor(82, 188, 105), 2, Qt::SolidLine));
            painter.drawLine(QPoint(prevPoint.x() + 33, prevPoint.y()), endPoint);

            // 箭头
            painter.drawLine(QLine(endPoint.x() - 5, endPoint.y() - 5, endPoint.x(), endPoint.y()));
            painter.drawLine(QLine(endPoint.x() - 5, endPoint.y() + 5, endPoint.x(), endPoint.y()));
        }
    }
}

void LinkedListVisualWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制背景
    painter.fillRect(rect(), QColor(250, 255, 255));

    // 计算绘图区域
    computeDrawArea();

    // 绘制链表节点
    for (int i = 0; i < m_drawNodesSize; i++) {
        drawNode(painter, m_drawNodes[i], i);
    }

    // 绘制NULL节点
    if (m_drawNodesSize > 0) {
        painter.setPen(QPen(Qt::black, 2, Qt::SolidLine));
        QFont font("Microsoft YaHei", 15, QFont::Bold);
        painter.setFont(font);
        painter.drawText(m_nullRect, Qt::AlignCenter, "NULL");
    }

    // 绘制新节点
    drawNewNode(painter);

    // 绘制断开连接
    if (m_breakConnection && m_breakNode) {
        // 找到断开节点的位置
        ListNode* current = m_head;
        int breakIndex = 0;
        while (current && current != m_breakNode) {
            current = current->next;
            breakIndex++;
        }

        if (breakIndex < m_drawNodesSize) {
            QPoint breakPoint = m_drawNodes[breakIndex].point;
            QPoint arrowPoint = QPoint(breakPoint.x() + 33, breakPoint.y());

            // 绘制断开符号
            painter.setPen(QPen(Qt::red, 3, Qt::SolidLine));
            painter.drawLine(QLine(arrowPoint.x() - 5, arrowPoint.y() - 5,
                                   arrowPoint.x() + 5, arrowPoint.y() + 5));
            painter.drawLine(QLine(arrowPoint.x() - 5, arrowPoint.y() + 5,
                                   arrowPoint.x() + 5, arrowPoint.y() - 5));
        }
    }

    // 绘制head指针
    if (m_head && m_drawNodesSize > 0) {
        painter.setPen(QPen(Qt::red, 2, Qt::SolidLine));
        QFont font("Microsoft YaHei", 12);
        painter.setFont(font);

        QRect headRect = m_drawNodes[0].rectLeft;
        headRect.setY(headRect.y() + 50);
        headRect.setHeight(20);
        painter.drawText(headRect, Qt::AlignCenter, "head");
    }
}

// ===================================================
// LinkedListWindow 实现
// ===================================================

// ---------------------------------------------------
// Constructor / Destructor
// ---------------------------------------------------
LinkedListWindow::LinkedListWindow(QWidget *parent)
    : QMainWindow(parent),
    m_head(nullptr),
    m_size(0),
    m_animationTimer(nullptr),
    m_animationStep(0),
    m_currentValue(0),
    m_targetPosition(0),
    m_currentPosition(0),
    m_currentNode(nullptr),
    m_previousNode(nullptr),
    m_found(false),
    m_newNode(nullptr),
    m_showNewNode(false),
    m_breakConnection(false),
    m_breakNode(nullptr),
    m_deleteSuccess(false),
    m_operationType(""),
    m_tempNode(nullptr)
{
    setupUI();

    // 创建示例链表: 1 -> 3 -> 5 -> 7
    m_head = new ListNode(1);
    ListNode* node2 = new ListNode(3);
    ListNode* node3 = new ListNode(5);
    ListNode* node4 = new ListNode(7);

    m_head->next = node2;
    node2->next = node3;
    node3->next = node4;
    m_size = 4;

    updateDisplay();
}

LinkedListWindow::~LinkedListWindow()
{
    if (m_animationTimer) {
        m_animationTimer->stop();
        delete m_animationTimer;
    }
    clearList();
    if (m_newNode) {
        delete m_newNode;
    }
}

// ---------------------------------------------------
// UI Setup
// ---------------------------------------------------
void LinkedListWindow::setupUI()
{
    setWindowTitle("链表可视化演示");
    setMinimumSize(1000, 600);
    resize(1000, 600);

    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);

    // 创建主分割器，将界面分为左右两部分
    QSplitter *mainSplitter = new QSplitter(Qt::Horizontal, centralWidget);
    mainLayout->addWidget(mainSplitter);

    // 左侧：可视化展示区
    QWidget *leftWidget = new QWidget(mainSplitter);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftWidget);

    QLabel *visualLabel = new QLabel("链表可视化:", leftWidget);
    leftLayout->addWidget(visualLabel);

    m_visualizationWidget = new QWidget(leftWidget);
    m_visualizationWidget->setMinimumSize(500, 500);
    leftLayout->addWidget(m_visualizationWidget);

    mainSplitter->addWidget(leftWidget);

    // 右侧：操作区和信息展示区
    QWidget *rightWidget = new QWidget(mainSplitter);
    QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);

    // 返回主菜单按钮（右上方）
    QPushButton *returnBtn = new QPushButton("返回主菜单", rightWidget);
    rightLayout->addWidget(returnBtn);

    // 操作按钮栏
    QGroupBox *opsGroup = new QGroupBox("链表操作", rightWidget);
    QVBoxLayout *opsLayout = new QVBoxLayout(opsGroup);

    // 初始化数据按钮
    QPushButton *inputBtn = new QPushButton("初始化数据", opsGroup);
    opsLayout->addWidget(inputBtn);

    // 插入操作按钮
    QPushButton *insertBtn = new QPushButton("插入元素", opsGroup);
    opsLayout->addWidget(insertBtn);

    // 删除操作按钮
    QPushButton *removeBtn = new QPushButton("删除元素", opsGroup);
    opsLayout->addWidget(removeBtn);

    // 查找操作按钮
    QPushButton *searchBtn = new QPushButton("查找元素", opsGroup);
    opsLayout->addWidget(searchBtn);

    // 清空按钮
    QPushButton *clearBtn = new QPushButton("清空链表", opsGroup);
    opsLayout->addWidget(clearBtn);

    rightLayout->addWidget(opsGroup);

    // 信息展示区
    QGroupBox *infoGroup = new QGroupBox("链表信息", rightWidget);
    QVBoxLayout *infoLayout = new QVBoxLayout(infoGroup);

    m_display = new QTextEdit(infoGroup);
    m_display->setReadOnly(true);
    m_display->setMinimumHeight(250);
    infoLayout->addWidget(m_display);

    rightLayout->addWidget(infoGroup);

    mainSplitter->addWidget(rightWidget);

    // 设置分割器比例，左侧占70%，右侧占30%
    mainSplitter->setStretchFactor(0, 7);
    mainSplitter->setStretchFactor(1, 3);

    // 初始化动画定时器
    m_animationTimer = new QTimer(this);
    m_animationTimer->setInterval(1000);
    connect(m_animationTimer, &QTimer::timeout, this, &LinkedListWindow::onAnimationStep);

    // 连接信号槽
    connect(inputBtn, &QPushButton::clicked, this, &LinkedListWindow::onInputData);
    connect(insertBtn, &QPushButton::clicked, this, &LinkedListWindow::onInsert);
    connect(removeBtn, &QPushButton::clicked, this, &LinkedListWindow::onRemove);
    connect(searchBtn, &QPushButton::clicked, this, &LinkedListWindow::onSearch);
    connect(clearBtn, &QPushButton::clicked, this, &LinkedListWindow::onClear);
    connect(returnBtn, &QPushButton::clicked, this, &LinkedListWindow::onReturnToMainMenu);
}

// ---------------------------------------------------
// 基本显示 / 可视化
// ---------------------------------------------------
void LinkedListWindow::onReturnToMainMenu()
{
    emit returnToMainMenu();
    this->close();
}

void LinkedListWindow::updateDisplay()
{
    QString info = QString("链表大小: %1\n\n").arg(m_size);
    info += "链表内容: ";

    ListNode* current = m_head;
    while (current != nullptr) {
        info += QString::number(current->data) + " -> ";
        current = current->next;
    }
    info += "NULL\n\n";

    // 添加链表详细信息
    info += "节点详情:\n";
    current = m_head;
    int index = 0;
    while (current != nullptr) {
        info += QString("节点 %1: 数据 = %2, 下一个 = %3\n")
                    .arg(index)
                    .arg(current->data)
                    .arg(current->next ? QString::number(current->next->data) : "NULL");
        current = current->next;
        index++;
    }

    m_display->setText(info);

    // 更新可视化
    if (m_visualizationWidget->layout()) {
        QLayout *layout = m_visualizationWidget->layout();
        QLayoutItem *item;
        while ((item = layout->takeAt(0)) != nullptr) {
            if (item->widget()) {
                item->widget()->setParent(nullptr);
                delete item->widget();
            }
            delete item;
        }
        delete layout;
    }

    LinkedListVisualWidget *visualWidget = new LinkedListVisualWidget(m_visualizationWidget);
    visualWidget->setLinkedListData(m_head, m_currentNode, m_previousNode, m_newNode,
                                    m_showNewNode, m_breakConnection, m_breakNode,
                                    m_operationType, m_animationStep, m_targetPosition);

    QVBoxLayout *layout = new QVBoxLayout(m_visualizationWidget);
    layout->addWidget(visualWidget);
    m_visualizationWidget->setLayout(layout);
}

// ---------------------------------------------------
// 内存操作与状态重置
// ---------------------------------------------------
void LinkedListWindow::clearList()
{
    ListNode* current = m_head;
    while (current != nullptr) {
        ListNode* next = current->next;
        delete current;
        current = next;
    }
    m_head = nullptr;
    m_size = 0;
}

void LinkedListWindow::resetAllHighlights()
{
    m_currentNode = nullptr;
    m_previousNode = nullptr;
    m_found = false;
    m_showNewNode = false;
    m_breakConnection = false;
    m_breakNode = nullptr;
    m_operationType = "";
    m_tempNode = nullptr;
    updateDisplay();
}

// ---------------------------------------------------
// 数据初始化 / UI 操作
// ---------------------------------------------------
void LinkedListWindow::onInputData()
{
    // 创建对话框让用户输入初始数据
    QDialog dialog(this);
    dialog.setWindowTitle("初始化链表数据");
    dialog.setFixedSize(400, 200);

    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    QLabel *label = new QLabel("请输入初始链表元素（用空格分隔的整数）:", &dialog);
    layout->addWidget(label);

    QLineEdit *dataEdit = new QLineEdit(&dialog);
    dataEdit->setPlaceholderText("例如: 10 20 30 40");
    layout->addWidget(dataEdit);

    QLabel *hintLabel = new QLabel("注意: 这将清空当前链表并创建新的链表", &dialog);
    hintLabel->setStyleSheet("color: red;");
    layout->addWidget(hintLabel);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    layout->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QString input = dataEdit->text().trimmed();

        if (input.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请输入至少一个整数");
            return;
        }

        // 解析输入的数据 - 使用原生数组替代 QList<int>
        QStringList numberStrings = input.split(' ', Qt::SkipEmptyParts);
        int* numbers = new int[numberStrings.size()];
        int numbersCount = 0;
        bool allValid = true;

        for (const QString& numStr : numberStrings) {
            bool ok;
            int num = numStr.toInt(&ok);
            if (ok) {
                numbers[numbersCount++] = num;
            } else {
                allValid = false;
                break;
            }
        }

        if (!allValid) {
            delete[] numbers;
            QMessageBox::warning(this, "输入错误", "请输入有效的整数，用空格分隔");
            return;
        }

        if (numbersCount == 0) {
            delete[] numbers;
            QMessageBox::warning(this, "输入错误", "请输入至少一个有效的整数");
            return;
        }

        // 清空当前链表
        clearList();

        // 创建新链表
        if (numbersCount > 0) {
            m_head = new ListNode(numbers[0]);
            ListNode* current = m_head;

            for (int i = 1; i < numbersCount; i++) {
                current->next = new ListNode(numbers[i]);
                current = current->next;
            }

            m_size = numbersCount;
        }

        delete[] numbers;
        resetAllHighlights();
        updateDisplay();
        QMessageBox::information(this, "初始化成功",
                                 QString("已成功初始化链表，包含 %1 个元素").arg(m_size));
    }
}

void LinkedListWindow::onInsert()
{
    QDialog dialog(this);
    dialog.setWindowTitle("插入元素");
    dialog.setFixedSize(300, 150);

    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    QLabel *label1 = new QLabel("插入位置 (0-" + QString::number(m_size) + "):", &dialog);
    layout->addWidget(label1);

    QLineEdit *posEdit = new QLineEdit(&dialog);
    posEdit->setPlaceholderText("插入位置");
    layout->addWidget(posEdit);

    QLabel *label2 = new QLabel("插入的值:", &dialog);
    layout->addWidget(label2);

    QLineEdit *valEdit = new QLineEdit(&dialog);
    valEdit->setPlaceholderText("插入的值");
    layout->addWidget(valEdit);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    layout->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QString posStr = posEdit->text().trimmed();
        QString valStr = valEdit->text().trimmed();

        if (posStr.isEmpty() || valStr.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请同时输入插入位置和插入值");
            return;
        }

        bool posOk, valOk;
        int position = posStr.toInt(&posOk);
        int value = valStr.toInt(&valOk);

        if (!posOk || !valOk) {
            QMessageBox::warning(this, "输入错误", "请输入有效的整数");
            return;
        }

        if (position < 0 || position > m_size) {
            QMessageBox::warning(this, "位置错误",
                                 QString("插入位置必须在 0 到 %1 之间").arg(m_size));
            return;
        }

        startInsertAnimation(value, position);
    }
}

void LinkedListWindow::onRemove()
{
    QDialog dialog(this);
    dialog.setWindowTitle("删除元素");
    dialog.setFixedSize(300, 120);

    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    QLabel *label = new QLabel("请输入要删除的元素值:", &dialog);
    layout->addWidget(label);

    QLineEdit *removeEdit = new QLineEdit(&dialog);
    removeEdit->setPlaceholderText("要删除的元素");
    layout->addWidget(removeEdit);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    layout->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QString input = removeEdit->text();
        if (input.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请输入要删除的元素");
            return;
        }

        bool ok;
        int value = input.toInt(&ok);
        if (ok) {
            startRemoveAnimation(value);
        } else {
            QMessageBox::warning(this, "输入错误", "请输入有效的整数");
        }
    }
}

void LinkedListWindow::onSearch()
{
    QDialog dialog(this);
    dialog.setWindowTitle("查找元素");
    dialog.setFixedSize(300, 120);

    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    QLabel *label = new QLabel("请输入要查找的元素:", &dialog);
    layout->addWidget(label);

    QLineEdit *searchEdit = new QLineEdit(&dialog);
    searchEdit->setPlaceholderText("要查找的元素");
    layout->addWidget(searchEdit);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    layout->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QString input = searchEdit->text();
        if (input.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请输入要查找的元素");
            return;
        }

        bool ok;
        int value = input.toInt(&ok);
        if (ok) {
            startSearchAnimation(value);
        } else {
            QMessageBox::warning(this, "输入错误", "请输入有效的整数");
        }
    }
}

void LinkedListWindow::onClear()
{
    if (m_head == nullptr) {
        QMessageBox::information(this, "清空链表", "链表已经是空的");
        return;
    }

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认清空", "确定要清空链表吗？",
                                  QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        clearList();
        resetAllHighlights();
        updateDisplay();
        QMessageBox::information(this, "清空成功", "链表已清空");
    }
}

// ---------------------------------------------------
// 启动动画：插入 / 删除 / 查找
// ---------------------------------------------------
void LinkedListWindow::startInsertAnimation(int value, int position)
{
    if (m_animationTimer && m_animationTimer->isActive())
        m_animationTimer->stop();

    resetAllHighlights();
    m_operationType = "insert";
    m_currentValue = value;
    m_targetPosition = position;
    m_currentPosition = 0;
    m_animationStep = 0;
    m_currentNode = m_head;
    m_previousNode = nullptr;

    if (m_newNode) {
        delete m_newNode;
        m_newNode = nullptr;
    }
    m_newNode = new ListNode(value);
    m_showNewNode = true;
    m_breakConnection = false;
    m_breakNode = nullptr;

    m_animationTimer->start();
}

void LinkedListWindow::startRemoveAnimation(int value)
{
    if (m_animationTimer && m_animationTimer->isActive())
        m_animationTimer->stop();

    resetAllHighlights();
    m_operationType = "remove";
    m_currentValue = value;
    m_animationStep = 0;
    m_currentNode = m_head;
    m_previousNode = nullptr;
    m_deleteSuccess = false;
    m_breakConnection = false;
    m_breakNode = nullptr;
    m_tempNode = nullptr;

    m_animationTimer->start();
}

void LinkedListWindow::startSearchAnimation(int value)
{
    if (m_animationTimer && m_animationTimer->isActive())
        m_animationTimer->stop();

    resetAllHighlights();
    m_operationType = "search";
    m_currentValue = value;
    m_animationStep = 0;
    m_currentNode = m_head;
    m_previousNode = nullptr;
    m_found = false;

    m_animationTimer->start();
}

// ---------------------------------------------------
// 动画步进处理
// ---------------------------------------------------
void LinkedListWindow::onAnimationStep()
{
    if (m_operationType == "insert") {
        handleInsertStep();
    } else if (m_operationType == "remove") {
        handleRemoveStep();
    } else if (m_operationType == "search") {
        handleSearchStep();
    }

    updateDisplay();
}

// ---------------------------------------------------
// 插入动画（完全复制Python代码逻辑）
// ---------------------------------------------------
void LinkedListWindow::handleInsertStep()
{
    switch (m_animationStep) {
    case 0:
        m_display->append(QString("插入操作开始: 创建新节点，数据 = %1").arg(m_currentValue));
        m_display->append("新节点已创建，准备插入到位置 " + QString::number(m_targetPosition));
        m_animationStep++;
        break;

    case 1:
        m_display->append("取头指针指向的节点, index=0");
        m_currentNode = m_head;
        m_previousNode = nullptr;
        m_currentPosition = 0;
        m_animationStep++;
        break;

    case 2:
        if (m_targetPosition == 0) {
            m_display->append("在头部插入，跳过遍历");
            m_animationStep = 10;
            break;
        }

        if (m_currentNode == nullptr) {
            m_display->append("错误：位置超出范围");
            m_animationStep = 100;
            break;
        }

        if (m_currentPosition == m_targetPosition - 1) {
            m_display->append(QString("到达位置 %1，节点数据 = %2").arg(m_currentPosition).arg(m_currentNode->data));
            m_display->append("找到插入位置的前驱节点");
            m_animationStep = 20;
        } else {
            m_display->append(QString("位置是 %1").arg(m_currentPosition));
            m_display->append("  取该节点的next指针, index += 1");
            m_previousNode = m_currentNode;
            m_currentNode = m_currentNode->next;
            m_currentPosition++;
        }
        break;

    // 头部插入步骤
    case 10:
        m_display->append("头部插入 - 步骤1: 新节点的next指针指向原头节点");
        if (m_newNode) {
            m_newNode->next = m_head;
        }
        m_animationStep++;
        break;

    case 11:
        m_display->append("头部插入 - 步骤2: 将头指针指向新节点");
        m_head = m_newNode;
        m_size++;
        m_newNode = nullptr;
        m_showNewNode = false;
        m_animationStep = 100;
        break;

    // 中间插入详细步骤
    case 20:
        if (!m_currentNode) {
            m_display->append("错误：前驱节点不存在，插入失败");
            m_animationStep = 100;
            break;
        }

        m_display->append(QString("取到第%1位的指针").arg(m_currentPosition));
        m_previousNode = m_currentNode;
        m_animationStep++;
        break;

    case 21:
        m_display->append(QString("创建值为\"%1\"的节点").arg(m_currentValue));
        m_animationStep++;
        break;

    case 22:
        m_display->append("将新建节点的next指针指向原链表当前节点");
        if (m_newNode && m_previousNode) {
            m_newNode->next = m_previousNode->next;
        }
        m_animationStep++;
        break;

    case 23:
        m_display->append("将前驱节点的next指针指向新建节点");
        if (m_previousNode && m_newNode) {
            m_previousNode->next = m_newNode;
            m_size++;
            m_newNode = nullptr;
            m_showNewNode = false;
        }
        m_animationStep = 100;
        break;

    case 100:
        if (m_animationTimer && m_animationTimer->isActive())
            m_animationTimer->stop();
        m_display->append("插入操作完成");
        QMessageBox::information(this, "插入成功",
                                 QString("元素 %1 已成功插入到位置 %2").arg(m_currentValue).arg(m_targetPosition));
        resetAllHighlights();
        break;
    }
}

// ---------------------------------------------------
// 删除动画（详细展示指针指向动态过程）
// ---------------------------------------------------
void LinkedListWindow::handleRemoveStep()
{
    switch (m_animationStep) {
    case 0:
        m_display->append(QString("删除操作开始: 查找元素 %1").arg(m_currentValue));
        m_currentNode = m_head;
        m_previousNode = nullptr;
        m_animationStep++;
        break;

    case 1:
        if (m_currentNode == nullptr) {
            m_display->append("链表为空，无法删除");
            m_animationStep = 100;
            break;
        }
        m_display->append("从头节点开始遍历查找");
        m_animationStep++;
        break;

    case 2:
        if (m_currentNode->data == m_currentValue) {
            m_display->append(QString("找到要删除的节点，数据 = %1").arg(m_currentNode->data));
            if (m_previousNode == nullptr) {
                m_display->append("要删除的节点是头节点");
                m_animationStep = 10; // 删除头节点
            } else {
                m_display->append("要删除的节点是中间节点");
                m_animationStep = 20; // 删除中间节点
            }
        } else {
            m_display->append(QString("当前节点数据 = %1，不是要删除的节点").arg(m_currentNode->data));
            m_display->append("移动到下一个节点");
            m_previousNode = m_currentNode;
            m_currentNode = m_currentNode->next;

            if (m_currentNode == nullptr) {
                m_display->append("已到达链表末尾，未找到要删除的元素");
                m_animationStep = 100;
            }
        }
        break;

    // 删除头节点步骤
    case 10:
        m_display->append("删除头节点 - 步骤1: 将头指针指向当前节点的下一个节点");
        m_breakNode = m_head; // 标记要断开的节点
        m_breakConnection = true;
        m_animationStep++;
        break;

    case 11:
        m_display->append("删除头节点 - 步骤2: 更新头指针");
        m_tempNode = m_head;  // 使用成员变量
        m_head = m_head->next;
        m_display->append("头指针已更新");
        m_animationStep++;
        break;

    case 12:
        m_display->append("删除头节点 - 步骤3: 释放原头节点的内存");
        delete m_tempNode;
        m_tempNode = nullptr;  // 重置指针
        m_size--;
        m_currentNode = nullptr;
        m_breakConnection = false;
        m_animationStep = 100;
        break;

    // 删除中间节点步骤
    case 20:
        m_display->append("删除中间节点 - 步骤1: 将前驱节点的next指针指向当前节点的下一个节点");
        m_breakNode = m_currentNode; // 标记要断开的节点
        m_breakConnection = true;
        m_animationStep++;
        break;

    case 21:
        m_display->append("删除中间节点 - 步骤2: 更新前驱节点的next指针");
        m_previousNode->next = m_currentNode->next;
        m_display->append("前驱节点的next指针已更新");
        m_animationStep++;
        break;

    case 22:
        m_display->append("删除中间节点 - 步骤3: 释放当前节点的内存");
        delete m_currentNode;
        m_size--;
        m_currentNode = nullptr;
        m_breakConnection = false;
        m_animationStep = 100;
        break;

    case 100:
        if (m_animationTimer && m_animationTimer->isActive())
            m_animationTimer->stop();

        if (m_size == 0) {
            m_display->append("链表现在为空");
        }

        m_display->append("删除操作完成");
        QMessageBox::information(this, "删除完成",
                                 QString("元素 %1 删除操作已完成").arg(m_currentValue));
        resetAllHighlights();
        break;
    }
}

void LinkedListWindow::handleSearchStep()
{
    // 简化的查找逻辑
    switch (m_animationStep) {
    case 0:
        m_currentNode = m_head;
        m_previousNode = nullptr;
        m_found = false;
        m_display->append(QString("查找操作开始: 查找元素 %1").arg(m_currentValue));
        m_animationStep++;
        break;

    case 1:
        if (m_currentNode == nullptr) {
            m_display->append(QString("查找失败: 元素 %1 未找到").arg(m_currentValue));
            m_found = false;
            m_animationStep = 4;
            break;
        }
        if (m_currentNode->data == m_currentValue) {
            m_found = true;
            m_display->append(QString("查找成功: 元素 %1 已找到").arg(m_currentValue));
            m_animationStep = 4;
        } else {
            m_previousNode = m_currentNode;
            m_currentNode = m_currentNode->next;
            m_display->append(QString("移动到下一个节点"));
        }
        break;

    case 4:
        if (m_animationTimer && m_animationTimer->isActive())
            m_animationTimer->stop();
        if (m_found) {
            QMessageBox::information(this, "查找结果", QString("元素 %1 在链表中找到").arg(m_currentValue));
        } else {
            QMessageBox::information(this, "查找结果", QString("元素 %1 未找到").arg(m_currentValue));
        }
        QTimer::singleShot(2000, this, [this]() {
            resetAllHighlights();
            updateDisplay();
        });
        break;
    }
}
